import Dialog from 'tdesign-miniprogram/dialog/index';
import Toast from 'tdesign-miniprogram/toast/index';
import { CartGroupData, GoodsQuantity, DeleteGoods } from '../../services/cart/cart';

Page({
  data: {
    cartGroupData: { totalAmount: 0, isAllSelected: true, isNotEmpty: true, GoodsList: [], selectedGoodsCount: 0, InvalidGoods: [] },
    manageText: true,    // 管理
  },

  onShow() {
    this.getCartGroupData();
  },

  getCartGroupData() {
    let isEmpty = true;
    CartGroupData({}).then((res) => {
      if (res.code === '0000') {
        let cartGroupData = { totalAmount: 0, isAllSelected: true, isNotEmpty: true, GoodsList: [], selectedGoodsCount: 0, InvalidGoods: [] }
        if (res.data.length > 0) isEmpty = false;
        res.data.forEach(item => {
          if (item.isStatus === 1) cartGroupData.InvalidGoods.push(item);
          else cartGroupData.GoodsList.push(item);
        });
        cartGroupData.GoodsList.forEach(item => {
          if (item.isSelected == undefined) item.isSelected = true;
          if (item.isSelected) {
            cartGroupData.totalAmount += Number(item.totalAmount)
            cartGroupData.selectedGoodsCount += Number(item.count)
          }
        });
        cartGroupData.totalAmount = cartGroupData.totalAmount.toFixed(2)
        cartGroupData.isNotEmpty = !isEmpty;
        this.setData({ cartGroupData });
      }
    });
  },

  /* 数量增减 */
  onQuantityChange(e) {
    const { goods, quantity, goodsIndex } = e.detail;
    GoodsQuantity({ cartId: goods.id, price: goods.price, count: quantity }).then(res => {
      if (res.code == '0000') {
        let { GoodsList } = this.data.cartGroupData;
        GoodsList[goodsIndex].count = quantity;
        this.getTotal()
      }
    })
  },

  /* 检查当前项 */
  onGoodsSelect(e) {
    const { isSelected, goodsIndex } = e.detail;
    let cartGroupData = this.data.cartGroupData;
    cartGroupData.GoodsList[goodsIndex].isSelected = isSelected;
    if (cartGroupData.GoodsList.every((ite) => ite.isSelected === true)) cartGroupData.isAllSelected = true;
    else cartGroupData.isAllSelected = false;
    this.getTotal();
  },

  /* 检查商品全选项 */
  onSelectAll(event) {
    const { isAllSelected } = event.detail;
    let cartGroupData = this.data.cartGroupData;
    cartGroupData.GoodsList.forEach(item => {
      item.isSelected = isAllSelected
    });
    cartGroupData.isAllSelected = isAllSelected
    this.getTotal()
  },

  /* 检查总价与总件数 */
  getTotal() {
    let cartGroupData = this.data.cartGroupData;
    let totalAmount = 0;
    let selectedGoodsCount = 0;
    cartGroupData.GoodsList.forEach(item => {
      if (item.isSelected) {
        totalAmount += Number(item.count) * Number(item.price)
        selectedGoodsCount += Number(item.count)
      }
    });
    cartGroupData.totalAmount = totalAmount.toFixed(2);
    cartGroupData.selectedGoodsCount = selectedGoodsCount
    this.setData({ cartGroupData });
  },

  /* 商品详情 */
  goGoodsDetail(e) {
    const { goodsId } = e.detail.goods;
    wx.navigateTo({
      url: `/pages/goods/details/index?goodsId=${goodsId}`,
    });
  },

  /* 管理 */
  onManage() {
    this.setData({ manageText: !this.data.manageText });
  },

  // 单个删除
  onGoodsDelete(e) {
    const { goods } = e.detail;
    let cartIds = [goods.id];
    this.cartDelete(cartIds)
  },
  // 多个删除
  onGoodsDeletes() {
    let cartIds = [];
    const { GoodsList } = this.data.cartGroupData;
    GoodsList.forEach(item => {
      if (item.isSelected) cartIds.push(item.id);
    });
    this.cartDelete(cartIds)
  },
  /* 删除商品 */
  cartDelete(cartIds) {
    Dialog.confirm({
      content: '确认删除该商品吗?',
      confirmBtn: '确定',
      cancelBtn: '取消',
    }).then(() => {
      DeleteGoods({ cartIds }).then(res => {
        if (res.code == '0000') {
          Toast({ context: this, selector: '#t-toast', message: '删除成功' });
          this.getCartGroupData();
        }
      })
    });
  },

  /* 清空失效商品 */
  clearInvalidGoods() {
    let cartIds = [];
    const { InvalidGoods } = this.data.cartGroupData;
    InvalidGoods.forEach(item => {
      cartIds.push(item.id);
    });
    DeleteGoods({ cartIds }).then(res => {
      if (res.code == '0000') {
        Toast({ context: this, selector: '#t-toast', message: '删除成功' });
        this.getCartGroupData();
      }
    })
  },

  /* 结算 */
  onToSettle() {
    const goodsRequestList = [];
    const { GoodsList } = this.data.cartGroupData;
    GoodsList.forEach(item => {
      if (item.isSelected) goodsRequestList.push({ num: item.count, goodsId: item.goodsId })
    });
    wx.setStorageSync('order.goodsRequestList', JSON.stringify(goodsRequestList));
    wx.navigateTo({ url: '/pages/order/order-confirm/index' });
  },
  onGotoHome() {
    wx.switchTab({ url: '/pages/home/home' });
  },
});
